package com.taoyige.adapter;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.bean.Address;
import com.taoyige.bean.Order;
import com.taoyige.common.UIHelper;
import com.taoyige.ui.AddAddressActivity;
import com.taoyige.ui.AddressDetailActivity;
import com.taoyige.ui.BuyNowActivity;
import com.taoyige.widget.LoadingDialog;

/**
 * 用户地址Adapter类
 * 
 * @author zhuxun
 * @version 1.0
 * @created 2014-11-26
 */
public class ListAddressAdapter extends BaseAdapter {
	private Context context;// 运行上下文
	private AddressDetailActivity ac;
	private List<Address> addressList;// 数据集合
	private LayoutInflater listContainer;// 视图容器
	private int itemViewResource;// 自定义项视图源
	private Order order;
	private LoadingDialog loading;
	private Handler handlerA;
	private String userId;
	private int status=0;
	static class ListItemView { // 自定义控件集合
		public TextView userName;
		public TextView userAddress;
		public TextView userEdit;
		public ImageView userEditPic;
		public TextView userRemove;
		public ImageView userRemovePic;
		public Button useThisAddress;
	}

	/**
	 * 实例化Adapter
	 * 
	 * @param context
	 * @param data
	 * @param resource
	 */
	public ListAddressAdapter(AddressDetailActivity ac,Context context, List<Address> addressList, int resource,Order fromStatus,String userId,int status) {
		this.ac=ac;
		this.context = context;
		this.listContainer = LayoutInflater.from(context); // 创建视图容器并设置上下文
		this.itemViewResource = resource;
		this.addressList = addressList;
		this.order=fromStatus;
		this.userId=userId;
		this.status=status;
	}

	public int getCount() {
		return addressList.size();
	}

	public Object getItem(int arg0) {
		return null;
	}

	public long getItemId(int arg0) {
		return 0;
	}

	/**
	 * ListView Item设置
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		// 自定义视图
		ListItemView listItemView = null;

		if (convertView == null) {
			// 获取list_item布局文件的视图
			convertView = listContainer.inflate(this.itemViewResource, null);
			
			listItemView = new ListItemView();
			// 获取控件对象
			listItemView.useThisAddress = (Button) convertView
					.findViewById(R.id.user_this_address);
			
			if(order.getTotalPrice()==0.001){
				listItemView.useThisAddress.setVisibility(View.INVISIBLE);
			}
			listItemView.userName = (TextView) convertView
					.findViewById(R.id.user_address_name);
			listItemView.userAddress = (TextView) convertView
					.findViewById(R.id.user_address_value);
			listItemView.userRemove = (TextView) convertView
					.findViewById(R.id.user_address_remove_value);
			listItemView.userEdit = (TextView) convertView
					.findViewById(R.id.user_address_edit_value);
			listItemView.userEditPic = (ImageView) convertView
					.findViewById(R.id.user_address_edit);
			listItemView.userRemovePic = (ImageView) convertView
					.findViewById(R.id.user_address_remove);
			
			// 设置控件集到convertView
			convertView.setTag(listItemView);
		} else {
			listItemView = (ListItemView) convertView.getTag();
		}

		//展现对应的省市县
		Address address = addressList.get(position);
		final Address addressEdit = address;
		final String id = address.getId();
		listItemView.userName.setText(address.getName()+" "+address.getMobilephone());
		listItemView.userAddress.setText(address.getProvinceText()+address.getCityText()+address.getCountyText()+address.getDetails());
		listItemView.userEdit.setOnClickListener(new editClickListener(addressEdit));
		listItemView.userEditPic.setOnClickListener(new editClickListener(addressEdit));
		listItemView.userRemove.setTag(addressEdit);
		listItemView.userRemove.setOnClickListener(new delAddressListener(position,id));
		listItemView.userRemovePic.setTag(addressEdit);
		listItemView.userRemovePic.setOnClickListener(new delAddressListener(position,id));
		listItemView.useThisAddress.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				handlerA = new Handler() {
					public void handleMessage(Message msg) {
						if (loading != null)
							loading.dismiss();
						if (msg.what == 1 && msg.obj != null) {
							Address result = (Address) msg.obj;
							if(result.getResult().getErrorCode()==200){
								
								Intent intent = new Intent(context, BuyNowActivity.class);
								intent.putExtra("order", order);
								intent.putExtra("address", addressEdit);
								context.startActivity(intent);
								
								//ac.startActivityForResult(intent, 0);
							}else{
								UIHelper.ToastMessage(context, "网络异常,地址使用失败");
							}
						}else if (msg.obj != null) {
							((AppException) msg.obj).makeToast(context);
						}
					}
				};
				loading = new LoadingDialog(context);
				loading.show();
				new Thread() {
					public void run() {
						Message msg = new Message();
						try {
							Address result= ((AppContext) context.getApplicationContext()).setAddressDefault(id,userId);
							msg.what = 1;
							msg.obj = result;
						} catch (AppException e) {
							e.printStackTrace();
							msg.what = -1;
							msg.obj = e;
						}
						handlerA.sendMessage(msg);
					}
				}.start();
			}
		});
		return convertView;
	}
	
	class editClickListener implements OnClickListener{
		private Address address;
		public editClickListener(Address address1){
			this.address = address1;
		}
		@Override
		public void onClick(View v) {
				Intent intent = new Intent(context, AddAddressActivity.class);
				intent.putExtra("address", address);
				intent.putExtra("status",status);
				intent.putExtra("order",order);
				context.startActivity(intent);
				ac.finish();
		}
	}
	
	class delAddressListener implements OnClickListener{

		private int position;
		private String id;
		public delAddressListener(int position,String id){
			this.position=position;
			this.id=id;
		}
		@Override
		public void onClick(final View v) {
			final Address address = (Address) v.getTag();

			AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setTitle(R.string.msg_del_address_title);
			builder.setMessage(R.string.msg_del_address_msg);
			builder.setPositiveButton(R.string.sure,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							final  LoadingDialog loading = new LoadingDialog(context);
							final Handler handler = new Handler() {
								public void handleMessage(Message msg) {
									if (loading != null)
										loading.dismiss();
									if (msg.what == 1 ) {
										if(msg.obj!=null){
											Address ad=(Address) msg.obj;
											if(ad.getResult().getErrorCode()==200){
												//更新数据
												removeItem(position);
												UIHelper.ToastMessage(context, "已经删除该地址");
											}else{
												UIHelper.ToastMessage(context, "删除地址失败，请重试!");
											}
										}else{
											((AppException) msg.obj).makeToast(v.getContext());
										}
									} else{
										UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.app_run_code_error));
									}
									
								}
							};
							loading.show();
							new Thread() {
								public void run() {
									Message msg = new Message();
									try {
										Address result= ((AppContext) context.getApplicationContext()).delAddress(userId,id);
										if(result!=null&&result.getResult().getErrorCode()==200){
											msg.what = 1;
											msg.obj = result;
										}else{
											msg.what = -1;
											msg.obj = null;
										}
									} catch (AppException e) {
										e.printStackTrace();
										msg.what = -1;
										msg.obj = e;
									}
									handler.sendMessage(msg);
								}
							}.start();
						}
					});
			builder.setNegativeButton(R.string.cancle,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.show();
		}
	}
	
	private void removeItem(int position){
		addressList.remove(position);
        this.notifyDataSetChanged();
    }
}